//
//  NWOauthViewController.swift
//  Weibo
//
//  Created by Northwan on 16/1/22.
//  Copyright © 2016年 Northwan. All rights reserved.
//

import UIKit
import SVProgressHUD


let kAppkey = "2041413303"
let kAppSecret = "5c14b155b018b8c40cee417ae12fee08"
let kRedirectUri = "http://www.northwan.cn"
let kUsername = "570576534@qq.com"
let kPassword = "kaishi10.8"


class NWOauthViewController: UIViewController {
    
    private lazy var webview = UIWebView()
    
    
    override func loadView() {
        webview.delegate = self
        view = webview
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(kAppkey)&redirect_uri=\(kRedirectUri)"
        
        let request = NSURLRequest(URL: NSURL(string: urlString)!)
        
        webview.loadRequest(request)
    }
    
    private func setupUI(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: "dismiss")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: "autoFill")
        navigationItem.title = "微博登陆"
    }
    
    // MARK: - 点击事件
    @objc private func dismiss(){
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func autoFill(){
         let jsString = "document.getElementById('userId').value='\(kUsername)';" + "document.getElementById('passwd').value='\(kPassword)'"
         webview.stringByEvaluatingJavaScriptFromString(jsString)
    }
}

// MARK: - UIWebViewDelegate
extension NWOauthViewController:UIWebViewDelegate{
  
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let url = request.URL?.absoluteString else{
            return true
        }
        
        if !url.hasPrefix(kRedirectUri){
            return true
        }
        
        if request.URL!.query!.hasPrefix("code="){//授权
            let code = request.URL!.query!.substringFromIndex("code=".endIndex)
            NWUserAccountViewModel.sharedAccount.loadAccessToken(code, finished: { (isSuccessed) -> Void in
                if isSuccessed {
                  SVProgressHUD.dismiss()
                  self.dismissViewControllerAnimated(false, completion: { () -> Void in
                    //这里要注意的是要等控制器彻底关闭后再切换根控制器(bug)
                    NSNotificationCenter.defaultCenter().postNotificationName(kSwithRootCtrlNortif, object: self)
                  })
                }
            })
        }else{//取消授权
            dismiss()
        }
        
        return false
    }
}
